package com.swj.modules.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.swj.common.core.constant.UserConstants;
import com.swj.common.core.exception.ServiceException;
import com.swj.common.core.model.SysDictData;
import com.swj.common.core.model.SysDictType;
import com.swj.common.core.utils.SysStringUtil;
import com.swj.common.security.utils.DictUtils;
import com.swj.modules.system.mapper.SysDictDataMapper;
import com.swj.modules.system.mapper.SysDictTypeMapper;
import com.swj.modules.system.model.SysDictDataQueryVO;
import com.swj.modules.system.model.SysDictTypeQueryVO;
import com.swj.modules.system.service.ISysDictDataService;
import com.swj.modules.system.service.ISysDictTypeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 字典 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysDictTypeServiceImpl implements ISysDictTypeService {
    @Resource
    private SysDictTypeMapper dictTypeMapper;

    @Resource
    private SysDictDataMapper dictDataMapper;

    @Resource
    private ISysDictDataService dictDataService;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init() {
        loadingDictCache();
    }

    /**
     * 根据条件分页查询字典类型
     *
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeList(SysDictTypeQueryVO dictType) {
        return dictTypeMapper.selectList(getDictTypeQueryWrapper(dictType));
    }

    @Override
    public Page<SysDictType> selectDictTypePage(SysDictTypeQueryVO dictType) {
        Page<SysDictType> page = new Page<>(dictType.getPageNum(), dictType.getPageSize());
        return dictTypeMapper.selectPage(page, getDictTypeQueryWrapper(dictType));
    }

    private QueryWrapper<SysDictType> getDictTypeQueryWrapper(SysDictTypeQueryVO dictType){
        QueryWrapper<SysDictType> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(SysStringUtil.isNotBlank(dictType.getDictName()), "dict_name", dictType.getDictName())
                    .eq(SysStringUtil.isNotBlank(dictType.getStatus()), "status", dictType.getStatus())
                    .like(SysStringUtil.isNotBlank(dictType.getDictType()), "dict_type", dictType.getDictType())
                    .gt(Objects.nonNull(dictType.getBeginTime()), "create_time", dictType.getBeginTime())
                    .lt(Objects.nonNull(dictType.getEndTime()), "create_time", dictType.getEndTime())
                    .orderBy(true, true, "sort");
        return  queryWrapper;
    }

    /**
     * 根据所有字典类型
     *
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeAll() {
        return dictTypeMapper.selectList(new QueryWrapper<>());
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType) {
        List<SysDictData> dictData = DictUtils.getDictCache(dictType);
        if (SysStringUtil.isNotEmpty(dictData)) {
            return dictData;
        }
        SysDictDataQueryVO queryVO=new SysDictDataQueryVO();
        queryVO.setDictType(dictType);
        dictData = dictDataService.selectDictDataList(queryVO);
        if (SysStringUtil.isNotEmpty(dictData)) {
            DictUtils.setDictCache(dictType, dictData);
            return dictData;
        }
        return null;
    }

    /**
     * 根据字典类型ID查询信息
     *
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeById(String dictId) {
        return dictTypeMapper.selectById(dictId);
    }

    /**
     * 批量删除字典类型信息
     *
     * @param dictIds 需要删除的字典ID
     */
    @Override
    public void deleteDictTypeByIds(String[] dictIds) {
        for (String dictId : dictIds) {
            SysDictType dictType = selectDictTypeById(dictId);
            if (dictDataService.countDictDataByType(dictType.getDictType()) > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
            dictTypeMapper.deleteById(dictId);
            DictUtils.removeDictCache(dictType.getDictType());
        }
    }


    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache() {
        QueryWrapper<SysDictData> queryWrapper = new QueryWrapper<>();
        Map<String, List<SysDictData>> dictDataMap = dictDataMapper.selectList(queryWrapper).stream().collect(Collectors.groupingBy(SysDictData::getDictType));
        for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet()) {
            DictUtils.setDictCache(entry.getKey(), entry.getValue().stream().sorted(Comparator.comparing(SysDictData::getDictSort)).collect(Collectors.toList()));
        }
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache() {
        DictUtils.clearDictCache();
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache() {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    public boolean insertDictType(SysDictType dict) {
        int row = dictTypeMapper.insert(dict);
        if (row > 0) {
            DictUtils.setDictCache(dict.getDictType(), null);
        }
        return row > 0;
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDictType(SysDictType dict) {
        SysDictType oldDict = dictTypeMapper.selectById(dict.getId());
        int row = dictTypeMapper.updateById(dict);
        if (row > 0) {
            dictDataService.updateDictDataType(oldDict.getDictType(),dict.getDictType());
            QueryWrapper<SysDictData> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("dict_type", dict.getDictType())
                        .orderBy(true, true, "dict_sort");
            List<SysDictData> dictData = dictDataMapper.selectList(queryWrapper);
            if(!CollectionUtils.isEmpty(dictData)){
                DictUtils.setDictCache(dict.getDictType(), dictData);
            }
        }
        return row > 0;
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public String checkDictTypeUnique(SysDictType dict) {
        String dictId = SysStringUtil.isNull(dict.getId()) ? "-1" : dict.getId();
        QueryWrapper<SysDictType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SysStringUtil.isNotBlank(dict.getDictType()), "dict_type", dict.getDictType());
        SysDictType dictType = dictTypeMapper.selectOne(queryWrapper);
        if (SysStringUtil.isNotNull(dictType) && !dictType.getId().equals(dictId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
